var pageSize = 10;
var pageNum = 1;
var page;
var laypage;
var layer;



$(function () {
    $("#menuId").val(sessionStorage.menuId);
    var menuId = $("#menuId").val();
    if(sessionStorage.getItem(menuId+'add') == 1){
        $("#addBanner").css('display','inline');
    }
    // alert("000"+sessionStorage.menuId);
    layui.use(['laydate','element','laypage','layer'], function(){
        $ = layui.jquery;//jquery
        laydate = layui.laydate;//日期插件
        element = layui.element();//面包导航
        laypage = layui.laypage;//分页
        layer = layui.layer;//弹出层

        //以上模块根据需要引入

        var start = {
            // min: laydate.now(),
            max: '2099-06-16 23:59:59'
            ,istoday: true
            ,choose: function(datas){
                end.min = datas; //开始日选好后，重置结束日的最小日期
                end.start = datas //将结束日的初始值设定为开始日
            }
        };

        var end = {
            // min: laydate.now(),
            max: '2099-06-16 23:59:59'
            ,istoday: false
            ,choose: function(datas){
                start.max = datas; //结束日选好后，重置开始日的最大日期
            }
        };

        document.getElementById('LAY_demorange_s').onclick = function(){
            start.elem = this;
            laydate(start);
        }
        document.getElementById('LAY_demorange_e').onclick = function(){
            end.elem = this
            laydate(end);
        }
    });
    setTimeout(function () {
        findBannerList();
    },200);

});



//查询Banner列表
function findBannerList(){
    var menuId = $("#menuId").val();
    var startTime = $("#LAY_demorange_s").val();
    var endTime = $("#LAY_demorange_e").val();
    var phone = $("#phone").val();

    var params = {
        "type":"query",
        "menuId":menuId,
        "pageSize":pageSize,
        "pageNum":pageNum,
        "startTime":startTime,
        "endTime":endTime,
        "phone":phone
    };
    $.ajax({
        type:"post",
        url: "/advert/findBannerList",
        data:params,
        dataType: "json",
        success : function(data){
            if(data.code = 1 && data.code != undefined){
                var list = data.list;
                page = data.page;
                var html = "";
                for(var b in list){
                    var title = list[b].picTitle == undefined ? "" : list[b].picTitle;
                    var bannerType = "";
                    var flag = "";
                    if(list[b].bannerType == 1){
                        bannerType = "首页banner";
                    }else if(list[b].bannerType == 2){
                        bannerType = "首页功能icon";
                    }else if(list[b].bannerType == 3){
                        bannerType = "诗与远方banner";
                    }

                    if(list[b].flag == 0){
                        flag = "无效";
                    }else if(list[b].flag == 1){
                        flag = "有效";
                    }
                    html += '<tr><td>'+title+'</td>' +
                        '<td><img src="'+list[b].picUrl+'" style="width: 100px;"></td>' +
                        '<td style="word-wrap:break-word;word-break:break-all;width: 200px">'+list[b].secondLevelUrl+'</td>' +
                        '<td id="'+list[b].id+'pi">'+list[b].picIndex+'</td>' +
                        '<td>'+bannerType+'</td>' +
                        '<td>'+new Date(list[b].createTime).toLocaleString() +'</td>' +
                        '<td>'+(list[b].modifyTime == null ? "" : new Date(list[b].modifyTime).toLocaleString())+'</td>' +
                        '<td id="'+list[b].id+'flag">'+flag+'</td><td>';
                    if(sessionStorage.getItem(menuId+'edit') == 1){
                        html += '<button onclick="showUpdatePage('+list[b].id+','+list[b].picIndex+')" class="layui-btn layui-btn-normal">修改顺序</button>';
                        if(list[b].flag == 0){
                            html += '<button onclick="isFlag('+list[b].id+',this)" value="1" class="layui-btn layui-btn-normal">设为有效</button>';
                        }else {
                            html += '<button onclick="isFlag('+list[b].id+',this)" value="0" class="layui-btn layui-btn-warm">设为无效</button>';
                        }
                    }
                    if(sessionStorage.getItem(menuId+'del') == 1){
                        html += '<button onclick="showDelPage('+list[b].id+')" class="layui-btn layui-btn-danger">删除</button>';
                    }
                    html += '</td></tr>';
                }
                $("#bus").html(html);
                $("#total").html("共有数据："+page.total+" 条");
                laypage({
                    cont: 'page'
                    ,pages: page.pages
                    ,first: 1
                    ,curr:pageNum
                    ,last: page.pages
                    ,prev: '<em><</em>'
                    ,next: '<em>></em>'
                    ,jump: function (obj,first) {
                        pageNum = obj.curr;
                        if(!first){
                            findBannerList();
                        }
                    }
                });
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
            }else if(data.code == 2 && data.code != undefined){
                alert(data.message);
            }
        }

    });
}

//查询按钮
function search() {
    pageNum = 1;
    findBannerList();
}
//打开删除询问页面
var delIndex;
function showDelPage(id) {
    var html = "<div style='text-align: center'><p style='margin-bottom: 30px'>确定删除吗?</p><button onclick='delBanner("+id+","+1+",this)' class='layui-btn layui-btn-normal'>确定</button><button onclick='delBanner("+id+","+2+",this)' class='layui-btn layui-btn-normal' style='background-color: #ff5722;margin-left: 100px'>取消</button></div>"
    delIndex = layer.open({
        title: ['提示','color: #2299ee;border-bottom: 1px solid;']
        ,type: 1
        ,content: html
        ,area: ['300px', '150px']
        ,maxmin:true
    });
}
//删除
function delBanner(id,index,obj) {
    $(obj).attr("disabled",true);
    if(index == 2){
        layer.close(delIndex);
        return false;
    }
    var menuId = $("#menuId").val();
    var params = {
        "type":"del",
        "menuId":menuId,
        "id":id
    };
    $.ajax({
        type:"post",
        url:"/advert/delBanner",
        data:params,
        dataType:"json" ,
        success :function (data) {

            if(data.code == 1 && data.code != undefined){
                alert("删除成功");
                layer.close(delIndex);
                findBannerList();
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
                $(obj).attr("disabled",false);
            }else if(data.code == 2 && data.code != undefined){
                alert("删除失败");
                $(obj).attr("disabled",false);
            }
        }
    });
}
//打开修改页面
var updateIndex;
function showUpdatePage(id,pi) {
    var html = "<div style='text-align: center'><label>图片序号</label><input id='bpi' value='"+pi+"' style='height: 30px;margin-top: 20px;text-align: center'/><br/><button onclick='updateBanner("+id+",this)' class='layui-btn layui-btn-normal' style='margin-top: 48px;margin-left: 401px'>确定</button></div>"
    updateIndex = layer.open({
        title: ['编辑banner','color: #2299ee;border-bottom: 1px solid;']
        ,type: 1
        ,content: html
        ,area: ['500px', '200px']
        ,maxmin:true
    });
}
//修改图片序号
function updateBanner(id,obj) {
    $(obj).attr("disabled",true);

    var bpi = $("#bpi").val();
    if(isNaN(bpi)){
        alert("序号填写错误");
        $(obj).attr("disabled",false);
        return false;
    }
    var menuId = $("#menuId").val();
    var params = {
        "type":"change",
        "menuId":menuId,
        "id":id,
        "picIndex":bpi
    };
    $.ajax({
        type:"post",
        url:"/advert/updateBanner",
        data:params,
        dataType:"json" ,
        success :function (data) {

            if(data.code == 1 && data.code != undefined){
                alert("修改成功");
                layer.close(updateIndex);
                $("#"+id+"pi").html(bpi);
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
                $(obj).attr("disabled",false);
            }else if(data.code == 2 && data.code != undefined){
                alert("修改失败");
                $(obj).attr("disabled",false);
            }
        }
    });
}
//设置是否有效
function isFlag(id,obj) {
    $(obj).attr("disabled",true);

    var flag = $(obj).val();
    var bpi = $("#bpi").val();
    var menuId = $("#menuId").val();
    var params = {
        "type":"change",
        "menuId":menuId,
        "id":id,
        "flag":flag
    };
    $.ajax({
        type:"post",
        url:"/advert/updateBanner",
        data:params,
        dataType:"json" ,
        success :function (data) {

            if(data.code == 1 && data.code != undefined){
                alert("修改成功");
                if(flag == 0){
                    $(obj).val(1);
                    $(obj).html("设为有效");
                    $(obj).attr("class","layui-btn layui-btn-normal");
                    $("#"+id+"flag").html("无效");
                }else if(flag == 1){
                    $(obj).val(0);
                    $(obj).html("设为无效");
                    $(obj).attr("class","layui-btn layui-btn-warm");
                    $("#"+id+"flag").html("有效");
                }
                $(obj).attr("disabled",false);
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
                $(obj).attr("disabled",false);
            }else if(data.code == 2 && data.code != undefined){
                alert("修改失败");
                $(obj).attr("disabled",false);
            }
        }
    });
}
//打开添加页面
var addIndex;
function showAddPage() {
    var html = '<table style="border-collapse: separate;border-spacing: 10px"><tr><td style="float: right">图片标题</td><td><input id="picTitle" style="height: 30px;width: 260px"/></td></tr>' +
        '<tr><td style="float: right">图片类型</td><td><select id="bannerType" style="height: 30px;width: 260px"><option value="1">首页banner</option><option value="2">首页功能ioc</option><option value="3">诗与远方banner</option></select></td></tr>'+
        '<tr><td style="float: right">banner图片对应的二级链接地址</td><td><input id="secondLevelUrl" style="height: 30px;width: 260px"/></td></tr>'+
        "<tr style='height: 100px'><td style='float: right'><button onclick='image.click()' class='layui-btn layui-btn-normal' style='margin-top: 40px'>点击上传banner图片</button></td><td><input onchange='preview(this,1)' id='image' type='file' style='display: none'/>"+
        '<div id="preview1" style="width: 260px;height: 100px;text-align: center;display: inline-block"></div></td></tr></table>'+
        "<button onclick='addBanner(this)' class='layui-btn layui-btn-normal' style='float: right;margin-right: 10px;margin-top: 57px'>提交</button>";
    addIndex = layer.open({
        title: ['添加banner','color: #2299ee;border-bottom: 1px solid;']
        ,type: 1
        ,content: html
        ,area: ['600px', '400px']
        ,maxmin:true
    });
}
//图片预览
function preview(file, id) {
    var prevDiv = document.getElementById('preview' + id);
    var fileType = file.files[0].type;
    if(fileType != "image/pjpeg" && fileType != "image/jpeg" && fileType != "image/x-png" && fileType != "image/png"){
        alert("图片类型错误");
        return false;
    }
    if (file.files && file.files[0]) {
        var reader = new FileReader();
        reader.onload = function (evt) {
            prevDiv.innerHTML = '<img src="' + evt.target.result + '" style="width: 260px;height: 100px;"/>';
        }
        reader.readAsDataURL(file.files[0]);
    } else {
        prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
    }
}
//添加banner
function addBanner(obj) {
    $(obj).attr("disabled",true);

    var picTitle = $("#picTitle").val();
    if(picTitle == "" || picTitle == undefined){
        alert("请填写标题");
        $(obj).attr("disabled",false);
        return false;
    }
    var bannerType = $("#bannerType").val();
    var secondLevelUrl = $("#secondLevelUrl").val();
    if(secondLevelUrl == "" || secondLevelUrl == undefined){
        alert("请填写二级链接");
        $(obj).attr("disabled",false);
        return false;
    }
    var file = $("#image")[0].files[0];
    if(file == undefined){
        alert("请上传图片");
        $(obj).attr("disabled",false);
        return false;
    }
    var menuId = $("#menuId").val();
    var formData = new FormData();
    formData.append("type","add");
    formData.append("menuId",menuId);
    formData.append("picTitle",picTitle);
    formData.append("bannerType",bannerType);
    formData.append("file",file);
    formData.append("secondLevelUrl",secondLevelUrl);


    $.ajax({
        type:"post",
        url:"/advert/addBanner",
        data:formData,
        processData : false,
        contentType : false,
        dataType:"json" ,
        success :function (data) {

            if(data.code == 1 && data.code != undefined){
                alert("添加成功");
                layer.close(addIndex);
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
                $(obj).attr("disabled",false);
            }else if(data.code == 2 && data.code != undefined){
                alert("添加失败");
                $(obj).attr("disabled",false);
            }
        }
    });
}